<template>
  <!--这是右击菜单组件-->
  <div v-if="flag" :style="styleN" class="contextMenu">
    <ul>
      <li v-for="item in dataM" :v-if="dataM.length !==0" :key="item.id" @click="handleMenuItem(item)">
        <svg class="icon" aria-hidden="true">
          <use :xlink:href="item.icon"/>
        </svg>
        <span>{{ item.title }}</span>
      </li>
      <li v-if="dataM.length ===0">
        <span>暂无数据</span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    // target: '',
    // 传入菜单数据
    /*
    * { icon: "el-icon-back", title: "关闭左侧", id: "left" }
    * */
    dataM: {
      type: Array,
      default: function() {
        return []
      }
    },
    // 是否显示
    showV: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    flag: {
      get() {
        if (this.showV) {
          // 注册全局监听事件 [ 目前只考虑鼠标解除触发 ]
          console.log('子组件1' + this.showV)
          window.addEventListener('mousedown', this.watchContextmenu)
        }
        return this.showV
      },
      set(newVal) {
        this.$emit('update:showV', newVal)
      }
    },
    styleN() {
      return {
        left: this.target !== null ? this.target.clientX + 'px' : '0px',
        top: this.target !== null ? this.target.clientY + 'px' : '0px',
        display: this.showV ? 'block' : 'none'
      }
    }
  },
  mounted() {
    // 将菜单放置到body下,解决相对于谁进行定位
    document.querySelector('body').appendChild(this.$el)
  },
  methods: {
    // 菜单点击事件
    handleMenuItem(item) {
      this.$emit('rowClick', item)
    },
    watchContextmenu() {
      this.flag = false
      window.removeEventListener('mousedown', this.watchContextmenu)
    }
  }
}
</script>

<style lang="scss" scoped>
.contextMenu {
  position: absolute;
  z-index: 3000;
  padding: 5px 0;
  font-size: 14px;
  font-weight: 400;
  color: #333;
  border-radius: 4px;
  background-color: #FFF;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
  ul {
    padding: 0;
    margin: 0;
    li {
      list-style: none;
      margin: 0;
      padding: 5px 10px;
      cursor: pointer;
      span {
        margin-left: 10px;
      }
    }
    li:hover {
      background-color: #F2F2F2;
    }
  }
}
</style>
